package leetcode.medium.q8;

import lombok.extern.slf4j.Slf4j;

//字符串转换整数 (atoi)
@Slf4j
public class Q {
    public static void main(String[] args) {
        log.info("{}", new Solution().myAtoi("62"));
        log.info("{}", new Solution().myAtoi(String.valueOf(Integer.MAX_VALUE)+"1"));
    }
}

/**
 * 通过除法以及减法操作，可以有效的保证在Integer取值范围内做比较不会越界
 */
class Solution {
    public int myAtoi(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        int length = s.length();
        int result = 0;
        Boolean isNegative = null;
        for (int i = 0; i < length; i++) {
            char ch = s.charAt(i);
            if (ch >= '0' && ch <= '9') {
                if (isNegative == null) {
                    isNegative = false;
                }
                if (result == 0) {
                    result = ch - 48;
                } else {
                    if (!isNegative) {
                        if (Integer.MAX_VALUE / result >= 10 && Integer.MAX_VALUE - result * 10 > ch - 48) {
                            result = (result * 10 + ch - 48);
                        } else {
                            return Integer.MAX_VALUE;
                        }
                    } else {
                        if (Integer.MAX_VALUE / result >= 10 && Integer.MAX_VALUE - result * 10 + 1 > ch - 48) {
                            result = result * 10 + ch - 48;
                        } else {
                            return Integer.MIN_VALUE;
                        }
                    }
                }

            } else if (ch == '-' && isNegative == null) {
                isNegative = true;
            } else if (ch == '+' && isNegative == null) {
                isNegative = false;
            } else if (ch == ' ' && isNegative == null) {
                continue;
            } else {
                break;
            }
        }
        return result;

    }
}